﻿using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;

namespace MaxStoreErp.Core.Ui.Drop
{
    public class DropHelper
    {
        public static string GetDroppedFile(IDataObject dropObject, out FileSource fileSource)
        {
            var fileDropList = (string[])dropObject.GetData(DataFormats.FileDrop, false);
            if (fileDropList != null)
            {
                fileSource = FileSource.Local;
                return fileDropList[0];
            }

            var formats = dropObject.GetFormats();
            if (formats.Contains("text/html"))
            {
                var obj = dropObject.GetData("text/html");
                var html = string.Empty;
                var s = obj as string;
                if (s != null)
                {
                    html = s;
                }
                else
                {
                    var memoryStream = obj as MemoryStream;
                    if (memoryStream != null)
                    {
                        var ms = memoryStream;
                        var buffer = new byte[ms.Length];
                        ms.Read(buffer, 0, (int)ms.Length);
                        html = buffer[1] == 0 ? Encoding.Unicode.GetString(buffer) : Encoding.ASCII.GetString(buffer);
                    }
                }
                // Using a regex to parse HTML, but JUST FOR THIS EXAMPLE :-)
                var match = new Regex("<img.+?src=[\"'](.+?)[\"'].+?>").Match(html);
                if (match.Success)
                {
                    fileSource = FileSource.WebLink;
                    return (match.Groups[1].Value);
                }
            }

            fileSource = FileSource.Unknown;
            return string.Empty;
        }
    }

    public enum FileSource
    {
        Local,
        WebLink,
        Unknown
    }
}
